package com.wuxi.common.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * @author 33879
 */
@Configuration
@EnableCaching
public class CacheConfig {

    @Value("${cache.config.expired-time}")
    private Integer CACHE_EXPIRED_TIME;

    @Value("${cache.config.max-cache-num}")
    private Integer MAX_CACHE_NUM;

    @Bean
    public CaffeineCacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager();

        // 配置缓存参数
        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                // 过期时间：写入后多少分钟过期
                .expireAfterWrite(CACHE_EXPIRED_TIME, TimeUnit.MINUTES)
                // 最大缓存数量
                .maximumSize(MAX_CACHE_NUM);

        cacheManager.setCaffeine(caffeine);
        return cacheManager;
    }
}
